package com.ibiaoke.boss.controller;

import com.alibaba.fastjson.JSONObject;
import com.ibiaoke.boss.service.RegisterService;
import com.ibiaoke.common.base.BaseController;
import com.ibiaoke.common.configs.WeChatConfigs;
import com.ibiaoke.common.consts.WeChatConsts;
import com.ibiaoke.common.response.Res;
import com.ibiaoke.common.utils.AesCbcUtil;
import com.ibiaoke.common.utils.HttpUtil;
import com.ibiaoke.common.utils.SmsUtil;
import com.ibiaoke.customer.dao.CustomerDao;
import com.ibiaoke.customer.dao.ThirdPartLoginDao;
import com.ibiaoke.customer.entity.Customer;
import com.ibiaoke.customer.entity.ThirdPartLogin;
import com.ibiaoke.customer.service.CustomerService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
public class XcxLoginController extends BaseController {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private ThirdPartLoginDao  thirdPartLoginDao;

    @Autowired
    private RegisterService registerService;
    /**
     * 登陆
     * @return
     */
    @RequestMapping("/xcxLogin")
    @ResponseBody
    public Res login(String headImgUrl, String nickName, HttpServletRequest request,HttpServletResponse response) {
        String code = request.getParameter("code");
        String encryptedData = request.getParameter("encryptedData");
        String iv = request.getParameter("iv");
        if (StringUtils.isNotBlank(code)) {
            StringBuilder url = new StringBuilder();
            url.append("https://api.weixin.qq.com/sns/jscode2session?appid=");
            url.append(WeChatConfigs.getXcxAppId());
            url.append("&secret=");
            url.append(WeChatConfigs.getXcxAppSecret());
            url.append("&js_code=");
            url.append(code);
            url.append("&grant_type=authorization_code");
            String res = HttpUtil.httpClientGet(url.toString());
            if (StringUtils.isNotBlank(res)) {
                JSONObject jsonObj = JSONObject.parseObject(res);
                if (jsonObj.containsKey(WeChatConsts.OPEN_ID)) {
                    String unionid="";
                    String xcxOpenid = jsonObj.getString("openid");
                    String session_key = jsonObj.getString("session_key");
                    try {
                        String result  = AesCbcUtil.decrypt(encryptedData,session_key,iv,"UTF-8");
                        if (null != result && result.length() > 0) {
                            JSONObject userInfoJSON = JSONObject.parseObject(result);
                            if(userInfoJSON.get("unionId") != null){
                                unionid =userInfoJSON.get("unionId").toString();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    request.getSession().setAttribute("xcxOpenid",xcxOpenid);
                    request.getSession().setAttribute("unionid",unionid);
                    ThirdPartLogin thirdPartLogin = thirdPartLoginDao.getByUnid(unionid);
                    if(thirdPartLogin == null){
                        return new Res().addError("new_user").addResponse("sessionId",request.getSession().getId());
                    }else if(thirdPartLogin != null){
                        thirdPartLoginDao.updateByUnionid(unionid,xcxOpenid, headImgUrl, nickName);
                        Customer user = customerDao.getByMobile(thirdPartLogin.getMobile());
                        request.getSession().setAttribute("user",user);
                        request.getSession().setAttribute("openid",thirdPartLogin.getuId());
                        return new Res().addResponse("user",user)
                                .addResponse("thirdPartLogin",thirdPartLogin)
                                .addResponse("sessionId",request.getSession().getId());
                    }
                }
            }
        }
        return Res.create();
    }

    /**
     * 用户绑定手机号
     * @return
     */
    @RequestMapping(value = "/xcxBindMobile.do")
    @ResponseBody
    public Res xcxBindMobile(@RequestParam(value = "mobile") String mobile,
                             @RequestParam(value = "code") String code,
                             String headImgUrl, String nickName,HttpServletRequest request) {
        SmsUtil.validateMobileCode(mobile,code);
        Customer user = customerService.getCustomer(mobile);
        if(user==null){
            user = new Customer();
            user.setCustomerMobile(mobile);
            registerService.createNewCustomer(mobile, null);
            user = customerService.getCustomer(mobile);
        }
        ThirdPartLogin thirdPartyLogin = new ThirdPartLogin();
        thirdPartyLogin.setMobile(mobile);
        thirdPartyLogin.setxId((String) request.getSession().getAttribute("xcxOpenid"));
        thirdPartyLogin.setUnId((String) request.getSession().getAttribute("unionid"));
        thirdPartyLogin.setUserId(user.getCustomerId());
        thirdPartyLogin.setCreateTime(new Date());
        thirdPartyLogin.setHeadImageUrl(headImgUrl);
        thirdPartyLogin.setNickName(nickName);
        request.getSession().setAttribute("user", user);
        thirdPartLoginDao.insert(thirdPartyLogin);
        return new Res().addResponse("sessionId",request.getSession().getId())
                        .addResponse("thirdPartyLogin",thirdPartyLogin);
    }
}
